package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.mapper.PermissionMapper;
import com.itheima.pojo.Permission;
import com.itheima.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service(interfaceClass = PermissionService.class)
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 添加权限
     *
     * @param permission
     */
    @Override
    public void add(Permission permission) {
        permissionMapper.add(permission);
    }


    /**
     * 查询所有的权限
     *
     * @return
     */
    @Override
    public List<Permission> findAll() {
        List<Permission> list = permissionMapper.findAll();
        return list;
    }

    /**
     * 分页查询权限
     *
     * @param currentPage
     * @param pageSize
     * @param queryString
     * @return
     */
    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {

        //使用分页插件定义当前页和页面大小
        PageHelper.startPage(currentPage, pageSize);
        //条件查询权限数据
        List<Permission> list = permissionMapper.findByCondition(queryString);
        //将数据进行封装
        PageInfo<Permission> pageInfo = new PageInfo<>(list);
        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 根据id删除权限
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        //通过权限的id查询是否在中间表中被引用
        Integer count = permissionMapper.findCountByPermissionId(id);
        if (count > 0) {
            //抛出当前检查项被引用，不能删除
            throw new RuntimeException(MessageConstant.PERMISSION_IS_QUOTED);
        }
        //通过id删除检查项
        permissionMapper.deleteById(id);
    }

    /**
     * 根据id查询需要编辑的权限
     *
     * @param id
     * @return
     */
    @Override
    public Permission findById(Integer id) {
        //通过权限的id查询是否在中间表中被引用
        Integer count = permissionMapper.findCountByPermissionId(id);
        if (count > 0) {
            //抛出当前检查项被引用，不能编辑
            throw new RuntimeException(MessageConstant.EDIT_PERMISSION_IS_QUOTED);
        }
        Permission permission = permissionMapper.findById(id);
        return permission;
    }

    /**
     * 更新被编辑的权限
     *
     * @param permission
     */
    @Override
    public void edit(Permission permission) {
        permissionMapper.edit(permission);
    }

    /**
     * 在所有的权限信息中选中与角色对应的权限
     *
     * @param id
     * @return
     */
    @Override
    public List<Integer> findPermissionIdsByRole(Integer id) {
        List<Integer> permissionIds = permissionMapper.findCheckItemIdsByCheckGroupId(id);
        return permissionIds;
    }
}
